package com.ruoyi.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author: cyx
 * create: 2024/6/18 15:21
 **/
@Slf4j
public class HttpClientUtil {
    /**
     * 发送get请求
     *
     * @param url   请求URL
     * @param param 请求参数 key:value url携带参数 或者无参可不填
     * @return
     */
    public static Map<String ,Object> doGet(String url, Map<String, String> param ,Map<String ,String> headMap) {

        // 创建一个 LaxRedirectStrategy，这是一个不会处理重定向的策略
        LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy() {
            @Override
            public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
                // 总是返回 false，表示不处理任何重定向
                return false;
            }

//            @Override
//            public HttpHost determineRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
//                // 不需要实现，因为我们不处理重定向
//                return null;
//            }
        };

        // 创建一个 RequestConfig，设置不自动处理重定向
        RequestConfig requestConfig = RequestConfig.custom()
                .setRedirectsEnabled(false) // 禁用重定向
                .build();

        // 使用自定义的 redirectStrategy 和 requestConfig 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setRedirectStrategy(redirectStrategy)
                .setDefaultRequestConfig(requestConfig)
                .build();


        int index = 0;

        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();

        Map<String, Object> resultMap = new HashMap<>();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            for (Map.Entry<String ,String> head : headMap.entrySet()){
                String key = head.getKey();
                String value = head.getValue();
                httpGet.setHeader(key ,value);
            }

            response = httpClient.execute(httpGet);

            //获得响应码
            int responseCode = response.getStatusLine().getStatusCode();
            //获得响应字符串
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");

            resultMap.put("responseCode" ,responseCode);
            resultMap.put("resultString" ,resultString);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }

    /**
     * 无参数get请求
     *
     * @param url
     * @return
     */
    public static Map<String ,Object> doGet(String url) {
        return doGet(url, null ,null);
    }

    /**
     * 发送post请求
     *
     * @param url   请求URL
     * @param entityParam 请求参数 key:value
     * @return
     */
    public static String doPost(String url, Map<String, String> entityParam ,Map<String ,String> headParam) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (entityParam != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : entityParam.keySet()) {
                    paramList.add(new BasicNameValuePair(key, entityParam.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }


    /**
     * 发送post 请求
     *
     * @param url  请求地址
     * @param json 请求参数
     * @return
     */
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doPostJson(String url, String json ,Map<String ,String> headParam) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            for (String key : headParam.keySet()){
                httpPost.setHeader(key ,headParam.get(key));
            }
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }
}
